<template>
  <div class="admin-page container">
    <h1 class="page-title">管理员控制面板</h1>
    
    <!-- 登录表单 - 未登录时显示 -->
    <div v-if="!isAuthenticated" class="login-container">
      <h2>管理员登录</h2>
      <va-alert color="warning" icon="warning" class="mb-4">
        请先登录管理员账号
      </va-alert>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <va-input
          v-model="username"
          label="用户名"
          class="mb-4"
          placeholder="输入用户名"
          :error="!!usernameError"
          :error-messages="usernameError"
          @update:modelValue="usernameError = ''"
          required
        />
        
        <va-input
          v-model="password"
          label="密码"
          class="mb-4"
          placeholder="输入密码"
          type="password"
          :error="!!passwordError"
          :error-messages="passwordError"
          @update:modelValue="passwordError = ''"
          required
        />
        
        <div class="actions">
          <va-button type="submit" color="primary" :loading="isLoading">
            登录
          </va-button>
          <va-button to="/" flat>
            返回首页
          </va-button>
        </div>
        
        <div class="info-text">
          <p>默认管理员账户：admin / memeking</p>
        </div>
      </form>
    </div>
    
    <!-- 管理员面板 - 登录后显示 -->
    <div v-else>
      <div class="admin-panel">
        <div class="panel-header">
          <h2>导入管理</h2>
          <div class="user-info">
            <va-avatar :color="getAvatarColor" size="small">{{ userInitial }}</va-avatar>
            <span class="username">{{ user?.username }}</span>
            <va-button @click="handleLogout" small flat icon="logout">退出</va-button>
          </div>
        </div>
        
        <!-- 导入表单 -->
        <div class="import-section panel-section">
          <h3 class="section-title">导入表情</h3>
          
          <div class="import-instructions">
            <p>将表情包图片放入后端服务器的 <code>uploads/import</code> 目录中，然后点击下方的导入按钮开始导入。</p>
            <p>导入时系统会自动进行 AI 分析，为每张图片生成相关标签。</p>
          </div>
          
          <form 
          style="display: flex; flex-direction: row; gap: 10px; align-items: center;"
          @submit.prevent="handleImport" class="import-form">
            <va-input
              v-model="dateFolder"
              label="目标日期 (可选)"
              class="mb-4"
              placeholder="YYYYMMDD 格式，例如: 20240401"
              :error="!!dateError"
              :error-messages="dateError"
              @update:modelValue="dateError = ''"
            />
            
            <va-checkbox
              v-model="analyzeImages"
              label="使用 AI 分析生成图片标签"
            />
            
            <div class="actions">
              <va-button type="submit" color="primary" :loading="importLoading">
                开始导入
              </va-button>
            </div>
          </form>
          
          <!-- 导入结果 -->
          <va-alert v-if="importMessage.text" :color="importMessage.type" icon="info" class="mt-4">
            {{ importMessage.text }}
          </va-alert>
          
        </div>
        
        <!-- 最近导入的表情包 -->
        <div class="recent-imports panel-section">
          <h3 class="section-title">
            最近导入
            <va-button 
              icon="refresh" 
              small 
              flat 
              class="refresh-button"
              :loading="recentImportsLoading"
              @click="loadRecentImports"
            >
              刷新
            </va-button>
          </h3>
          
          <va-alert v-if="recentImportsError" color="danger" icon="error" class="mb-4">
            {{ recentImportsError }}
          </va-alert>
          
          <va-data-table 
            :items="recentImports" 
            :columns="columns"
            :loading="recentImportsLoading"
            class="recent-imports-table"
          >
            <template #cell(preview)="{ rowData }">
              <div class="preview-cell">
                <img :src="rowData.url" :alt="rowData.originalName" class="preview-image" />
              </div>
            </template>
            <template #cell(tags)="{ rowData }">
              <TagEditor 
                v-model="rowData.tags" 
                :itemId="rowData.id"
                @tags-updated="onTagsUpdated"
              />
            </template>
          </va-data-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, inject } from 'vue'
import { importFiles, getRecentImports, syncTags } from '../api/uploads'
import { useAuth } from '../composables/useAuth'
import TagEditor from '../components/TagEditor.vue'
import { API_BASE_URL } from '../config/api'

console.log('AdminPage 组件开始加载')

// 使用注入的全局认证状态
const auth = inject('auth')
const { 
  isAuthenticated, 
  user, 
  login, 
  logout, 
  isLoading, 
  error: authError,
  checkAuth
} = auth

console.log('认证状态:', isAuthenticated.value, '用户:', user.value)

// 登录表单
const username = ref('')
const password = ref('')
const usernameError = ref('')
const passwordError = ref('')

// 导入表单
const dateFolder = ref('')
const analyzeImages = ref(true)
const importLoading = ref(false)
const dateError = ref('')
const importMessage = ref({ text: '', type: 'info' })
const importResults = ref(null)

// 最近导入的表情包
const recentImports = ref([])
const recentImportsLoading = ref(false)
const recentImportsError = ref('')

// 数据表格列定义
const columns = [
  { key: 'preview', label: '预览' },
  { key: 'originalName', label: '文件名' },
  { key: 'tags', label: '标签' },
  { key: 'createdAt', label: '上传时间' },
  { key: 'actions', label: '操作' }
]

// 计算属性
const userInitial = computed(() => {
  return user.value?.username?.charAt(0).toUpperCase() || 'U'
})

const getAvatarColor = computed(() => {
  return user.value?.role === 'admin' ? 'primary' : 'secondary'
})

// 监视认证状态变化
watch(isAuthenticated, (newValue) => {
  if (newValue && user.value) {
    // 用户登录后自动加载数据
    loadRecentImports()
  }
})

// 登录处理
const handleLogin = async () => {
  // 验证输入
  let isValid = true
  
  if (!username.value) {
    usernameError.value = '请输入用户名'
    isValid = false
  }
  
  if (!password.value) {
    passwordError.value = '请输入密码'
    isValid = false
  }
  
  if (!isValid) return
  
  try {
    await login(username.value, password.value)
    // 登录成功后自动加载最近导入的表情
    loadRecentImports()
  } catch (error) {
    // 错误已在composable中处理
  }
}

// 登出处理
const handleLogout = async () => {
  await logout()
}

// 验证日期格式
const validateDate = (date) => {
  if (!date) return true // 日期是可选的
  
  // 检查格式是否为 YYYYMMDD
  if (!/^\d{8}$/.test(date)) {
    return false
  }
  
  // 验证是否为有效日期
  const year = parseInt(date.substring(0, 4))
  const month = parseInt(date.substring(4, 6)) - 1 // JS 月份从 0 开始
  const day = parseInt(date.substring(6, 8))
  
  const dateObj = new Date(year, month, day)
  return (
    dateObj.getFullYear() === year &&
    dateObj.getMonth() === month &&
    dateObj.getDate() === day
  )
}

// 导入处理
const isSyncingTags = ref(false)

/**
 * 同步标签数据到标签表
 */
const syncTagsData = async () => {
  if (isSyncingTags.value) return
  
  isSyncingTags.value = true
  
  try {
    await syncTags()
    // 可以添加一个通知或状态更新，但不影响主流程
  } catch (error) {
    console.error('标签同步失败:', error)
  } finally {
    isSyncingTags.value = false
  }
}

const handleImport = async () => {
  // 验证日期格式
  if (dateFolder.value && !validateDate(dateFolder.value)) {
    dateError.value = '请输入有效的日期格式 (YYYYMMDD)'
    return
  }
  
  importLoading.value = true
  importMessage.value = { text: '', type: 'info' }
  importResults.value = null
  
  try {
    const response = await importFiles({
      date: dateFolder.value || undefined,
      analyze_images: analyzeImages.value
    })
    
    importResults.value = response.data.results
    importMessage.value = { text: response.data.message, type: 'success' }
    
    // 导入成功后同步标签数据
    await syncTagsData()
    
    // 导入成功后重新加载最近导入的表情
    loadRecentImports()
  } catch (error) {
    const errorMsg = error.response?.data?.error || '导入失败，请检查后端服务'
    importMessage.value = { text: errorMsg, type: 'danger' }
  } finally {
    importLoading.value = false
  }
}

// 加载最近导入的表情
const loadRecentImports = async () => {
  if (!isAuthenticated.value) return
  
  recentImportsLoading.value = true
  recentImportsError.value = ''
  
  try {
    const response = await getRecentImports()
    // 修正图片URL路径，添加基础URL前缀
    const baseUrl = API_BASE_URL // 从配置中获取后端服务器基础URL
    recentImports.value = response.data.map(item => ({
      ...item,
      url: item.url.startsWith('http') ? item.url : `${baseUrl}${item.url}`
    }))
    console.log('已加载图片数据:', recentImports.value)
  } catch (error) {
    recentImportsError.value = '加载最近导入的表情失败'
    console.error('加载最近导入的表情失败:', error)
  } finally {
    recentImportsLoading.value = false
  }
}

// 组件加载时，如果已登录，自动加载最近导入的表情
onMounted(() => {
  console.log('AdminPage 组件已挂载')
  
  if (isAuthenticated.value) {
    console.log('用户已认证，加载导入数据')
    loadRecentImports()
  } else {
    console.log('用户未认证，显示登录表单')
  }
})

/**
 * 处理标签更新事件
 * @param {Array} tags - 更新后的标签数组
 */
const onTagsUpdated = (tags) => {
  // 标签已经在 TagEditor 组件内部保存和同步
  // 这里可以添加额外的处理逻辑，例如显示通知或刷新数据
  console.log('标签已更新:', tags)
}
</script>

<style scoped>
.admin-page {
  padding: 2rem 1rem;
}

.page-title {
  margin-bottom: 2rem;
  color: var(--primary-color);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.login-container {
  max-width: 500px;
  margin: 0 auto;
  background-color: white;
  padding: 2rem;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.login-form {
  margin-top: 1.5rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
  margin-bottom: 1.5rem;
}

.info-text {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.admin-panel {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background-color: var(--primary-color);
  color: white;
}

.panel-header h2 {
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.username {
  font-weight: 500;
}

.panel-section {
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 1.25rem;
  color: var(--primary-color);
}

.refresh-button {
  margin-left: 0.5rem;
}

.import-instructions {
  background-color: var(--border-color);
  padding: 1rem;
  border-radius: 0.5rem;
  margin-bottom: 1.5rem;
}

.import-instructions code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2rem 0.4rem;
  border-radius: 0.25rem;
  font-family: monospace;
}

.results-container {
  margin-top: 2rem;
  border-top: 1px solid var(--border-color);
  padding-top: 1.5rem;
}

.results-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 1rem;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: var(--primary-color);
}

.stat-label {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.preview-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 4px;
}

.tags-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem;
}

.tag-chip {
  font-size: 0.75rem;
}

.more-tags {
  font-size: 0.75rem;
  color: var(--text-secondary);
  margin-left: 0.25rem;
}
</style> 